package com.wtwd.wtwddevice.deviceserver.netty.code;


import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
public class WTDecoder  extends ByteToMessageDecoder {


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        //头部协议最少包含87个字节，不足87个字节，则意味这消息长度不足断包
        if (byteBuf.readableBytes() < 87) return;
        //获取当前读索引
        int idx = byteBuf.readerIndex();
        //创建与ByteBuf中可读字节数相同的数组
        byte[] bytes = new byte[byteBuf.readableBytes()];
        //计算读取时这一包的结束位置
        int total = idx + bytes.length;
        while (idx != total) {
            bytes[idx - byteBuf.readerIndex()] = byteBuf.getByte(idx++);
        }
        log.info("channelId:{}|设备数据:{}",ctx.channel().id(),new String(bytes, CharsetUtil.UTF_8));
        //标记当前读索引,出现数据不全时将读指针重置到该位置
        byteBuf.markReaderIndex();
        WTProtocol protocol = WTProtocol.builder().build()
                .initProtocol(byteBuf);
        if (protocol == null|| StringUtils.isEmpty(protocol.getImei())) { //协议创建失败
            if (byteBuf.readerIndex() == 0) { //断包
                byteBuf.resetReaderIndex();
            }
            return;
        }
        list.add(protocol);
    }
    public static void main(String[] args) {
        System.out.println("2@1@1@0@1@21@AC960_ZN_V03_240507@AC960_V1.0.8_2023-11-22_09-36-29".length());
    }
}